package com.songyuesheng.app.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songyuesheng.app.commom.ContextHolder;
import com.songyuesheng.app.mapper.NoticeMapper;
import com.songyuesheng.app.entity.Notice;
import com.songyuesheng.app.service.NoticeService;
import com.songyuesheng.app.commom.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    @Resource
    private NoticeMapper noticeMapper;

    @Override
    public Result<?> addNotice(Notice notice) {
        notice.setUserId(ContextHolder.getUserId());
        notice.setTime(DateUtil.now());
        notice.setOpen(true);
        int i = noticeMapper.insert(notice);
        return Result.success(i);
    }

    @Override
    public Result<?> updateNotice(Notice notice) {
        int i = noticeMapper.updateById(notice);
        return Result.success(i);
    }

    @Override
    public Result<?> deleteNotice(Integer id) {
        int i = noticeMapper.deleteById(id);
        return Result.success(i);
    }

    @Override
    public Result<?> selectAllNotice() {
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notice::getOpen, 1);
        List<Notice> notices = noticeMapper.selectList(queryWrapper);
        return Result.success(notices);
    }

    @Override
    public Result<?> selectNoticeByPage(Integer pageNum, Integer pageSize, String title) {
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(title), Notice::getTitle, title);
        Page<Notice> page = new Page<>(pageNum, pageSize);
        Page<Notice> noticePage = noticeMapper.selectPage(page, queryWrapper);
        return Result.success(noticePage);
    }

}
